package com.winit.common.manager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.util.Constants;
import com.winit.common.util.HttpClientUtil;
import com.winit.common.util.ShellRunUtil;
import com.winit.deploy.bean.DeployEnum;
import com.winit.deploy.manager.DeployManager;
import com.winit.deploy.util.DeployUtil;
import com.winit.project.core.bean.PackageTypeEnum;
import com.winit.project.core.bean.ProjectInfo;
import com.winit.project.core.branch.Project;
import com.winit.project.core.edition.PackageEdition;
import com.winit.project.manager.ProjectManager;
import com.winit.project.util.ProjectUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.List;

/**
 * Created by wangjian on 17/1/4.
 */
@Component
public class CommonManager {

    private static Logger logger = LoggerFactory.getLogger(CommonManager.class);

    @Autowired
    private ProjectManager projectManager;

    public void cleanReleaseDir() {
        try {
            List<ProjectInfo> list = projectManager.getProjectList(PackageTypeEnum.ALL, false, true);
            for (ProjectInfo info : list) {
                Project project = new Project(info.getProjectName(), true);
                List<PackageEdition> editions = project.listEditions(true, false);
                for (PackageEdition edition : editions) {
                    String path = edition.getPath();
                    File file = new File(path + "/release");
                    if (!file.exists()) {
                        continue;
                    }
                    String cmd = "find " + path + "/release -name \"*.war\" -o -name \"*.zip\" -mtime +2 -exec rm -rf {} \\;";
                    String str = ShellRunUtil.runCmds(cmd);
                    logger.info("com.winit.common.manager.CommonManager.cleanReleaseDir str=" + str);
                }
            }
        } catch (Exception e) {
            logger.error("com.winit.common.manager.CommonManager.cleanReleaseDir exception", e);
        }
    }

    public void cleanProject(String tokenId) {
        try {
            List<ProjectInfo> list = projectManager.getProjectList(PackageTypeEnum.ALL, false, true);
            for (ProjectInfo info : list) {
                Project project = new Project(info.getProjectName(), true);
                //1.不删主干
                if (project.isTrunk()) {
                    continue;
                }
                //2.不删线上分支
                String online = DeployUtil.getProjectVersion(project.getName(), DeployEnum.ONLINE, "projectName");
                if (online.equals(project.getFullName())) {
                    continue;
                }
                //3.不删staging分支
                String staging = DeployUtil.getProjectVersion(project.getName(), DeployEnum.STAGING, "projectName");
                if (staging.equals(project.getFullName())) {
                    continue;
                }
                //4.不删测试通过分支
                String testpass = DeployUtil.getProjectVersion(project.getName(), DeployEnum.TESTPASS, "projectName");
                if (testpass.equals(project.getFullName())) {
                    continue;
                }
                //5.有项目，并且正在进行中的不删
                //5.1 从beetle-plan获取工程关联项目
                JSONObject pro = HttpClientUtil.doGetForJson(Constants.BEETLE_PLAN_URL + "/project/getProjectInfo?token_id=" + tokenId + "&project_name=" + project.getFullName());
                if (null == pro) {
                    continue;
                }
                //查询失败或者应用没有plan_id则删除
                if (!pro.getBoolean("success") || StringUtils.isEmpty(pro.getJSONObject("data").getString("plan_id"))) {
                    //移除该分支
                    doMove(project);
                    continue;
                }
                JSONObject plan = HttpClientUtil.doGetForJson(Constants.BEETLE_PLAN_URL + "/project_plan/getPlanList?token_id=" + tokenId + "&isShowOnline=false&plan_id=" + pro.getJSONObject("data").getString("plan_id"));
                if (null == plan) {
                    continue;
                }
                JSONArray array = plan.getJSONArray("data");
                if (array.size() == 0) {
                    //移除该分支
                    doMove(project);
                }

            }
        } catch (Exception e) {
            logger.error("com.winit.common.manager.CommonManager.cleanProject exception", e);
        }
    }

    //移动应用
    private void doMove(Project project) {
        try {
            StringBuffer cmd = new StringBuffer();
            cmd.append("mkdir -p /home/beetle/Beetle_bak/projects/").append(project.getName())
                    .append(" && mv ").append(ProjectUtil.getTrunkFilePath(project.getName()))
                    .append(project.getFullName()).append("  /home/beetle/Beetle_bak/projects/").append(project.getName())
                    .append("/");
            String str = ShellRunUtil.runCmds(cmd.toString());
//            String str = "";
            logger.info("com.winit.common.manager.CommonManager.doMove cmd:" + cmd.toString() + " rtn:" + str);
        } catch (Exception e) {
            logger.error("com.winit.common.manager.CommonManager.doMove exception", e);
        }
    }

    public String recoverProject(String projectName) {
        try {
            StringBuffer cmd = new StringBuffer();
            cmd.append("mv /home/beetle/Beetle_bak/projects/").append(ProjectUtil.getTrunkProjectName(projectName))
                    .append("/").append(projectName).append("  /usr/local/Beetle/projects/")
                    .append(ProjectUtil.getTrunkProjectName(projectName)).append("/");
            String str = ShellRunUtil.runCmds(cmd.toString());
//            String str = "";
            logger.info("com.winit.common.manager.CommonManager.recoverProject cmd:" + cmd.toString() + " rtn:" + str);
            return str;
        } catch (Exception e) {
            logger.error("com.winit.common.manager.CommonManager.recoverProject exception", e);
            return e.getLocalizedMessage();
        }
    }
}
